package com.gengzp.rpc.factory.impl;

import com.gengzp.rpc.core.RpcRemoteTransactionRollbackProcessor;
import com.gengzp.rpc.factory.RpcBeanInstanceFactory;
import com.gengzp.rpc.interceptor.RpcRemoteCallInterceptor;
import com.gengzp.rpc.strategy.RpcRegisterCenterStrategy;
import com.gengzp.rpc.strategy.RpcRemoteServiceRouteStrategy;
import com.gengzp.rpc.tools.RpcEnvironmentVariableReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.gengzp.rpc.constants.RpcBeanNameConstants.*;

/**
 * @ClassName RpcBeanInstanceFactoryImpl
 * @Description rpc框架bean实例工厂实现类
 * @Author gengzp
 * @Date 2025/8/20 17:32
 */
@Component
public class RpcBeanInstanceFactoryImpl implements RpcBeanInstanceFactory {

    @Autowired
    private Map<String, RpcRemoteServiceRouteStrategy> rpcRemoteServiceRouteStrategyMap;

    @Autowired
    private Map<String, RpcRemoteCallInterceptor> rpcRequestInterceptorMap;

    @Autowired
    private Map<String, RpcRemoteTransactionRollbackProcessor> rpcRemoteTransactionRollbackProcessorMap;

    @Autowired
    private Map<String, RpcRegisterCenterStrategy> rpcRegisterCenterStrategyMap;

    @Override
    public RpcRemoteServiceRouteStrategy getRpcRemoteServiceRouteStrategy() {
        return rpcRemoteServiceRouteStrategyMap.get(RPC_REMOTE_SERVICE_ROUTE_STRATEGY_PREFIX +
                RpcEnvironmentVariableReader.getRegisterCenter().getName() +
                RPC_REMOTE_SERVICE_ROUTE_STRATEGY_SUFFIX);
    }

    @Override
    public RpcRemoteCallInterceptor getRpcRequestInterceptor() {
        if (rpcRequestInterceptorMap.size() == 1) {
            return rpcRequestInterceptorMap.values().iterator().next();
        }
        return rpcRequestInterceptorMap.get(
                rpcRequestInterceptorMap.keySet().stream()
                        .filter(key -> !key.equals(RPC_REQUEST_INTERCEPTOR_DEFAULT_IMPL))
                        .findFirst()
                        .orElseThrow()
        );
    }

    @Override
    public RpcRemoteTransactionRollbackProcessor getRpcRemoteTransactionRollbackProcessor() {
        if (rpcRemoteTransactionRollbackProcessorMap.size() == 1) {
            return rpcRemoteTransactionRollbackProcessorMap.values().iterator().next();
        }
        return rpcRemoteTransactionRollbackProcessorMap.get(
                rpcRemoteTransactionRollbackProcessorMap.keySet().stream()
                        .filter(key -> !key.equals(RPC_REMOTE_TRANSACTION_ROLLBACK_PROCESSOR_DEFAULT_IMPL))
                        .findFirst()
                        .orElseThrow()
        );
    }

    @Override
    public RpcRegisterCenterStrategy getRpcRegisterCenterStrategy(String registerCenterBeanName) {
        return rpcRegisterCenterStrategyMap.get(
                RPC_REGISTER_CENTER_STRATEGY_PREFIX + registerCenterBeanName + RPC_REMOTE_SERVICE_ROUTE_STRATEGY_SUFFIX);
    }

}
